package com.wjj.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wjj.entity.Brand;
import com.wjj.entity.Goods;
import com.wjj.entity.Shopping;
import com.wjj.service.GoodsService;

@Controller
public class GoodsController {
	@Autowired
	private GoodsService goodsService;
	
	//进入主页
	@RequestMapping("/")
	public String index() {
		return "index";
	}
	//添加品牌
	@RequestMapping("/addBrand")
	public String addBrand(Model model,Brand brand,MultipartFile file) throws IllegalStateException, IOException {
		if(file!=null && file.getSize()>0) {
			String originalFilename = file.getOriginalFilename();
			String fileName = UUID.randomUUID().toString().replaceAll("-", "")+originalFilename;
			File file2 = new File("D:/phone/",fileName);
			file.transferTo(file2);
			brand.setPic("/phone/"+fileName);
		}
		goodsService.addBrand(brand);
		return "redirect:/";
	}
	//追加
	@RequestMapping("/getBrand")
	@ResponseBody
	public List<Brand> getBrand() {
		
		List<Brand> list = goodsService.getBrand();
		return list;
	}
	//添加商品
	@RequestMapping("/addGoods")
	public String addGoods(Model model,Goods goods,MultipartFile file) throws IllegalStateException, IOException {
		if(file!=null && file.getSize()>0) {
			String originalFilename = file.getOriginalFilename();
			String fileName = UUID.randomUUID().toString().replaceAll("-", "")+originalFilename;
			File file2 = new File("D://phone",fileName);
			file.transferTo(file2);
			goods.setPic("/phone/"+fileName);
		}
		goodsService.addGoods(goods);
		return "redirect:/";
	}
	//购买商品,,查询所有的品牌
	@RequestMapping("/Goods")
	public String Brand(Model model) {
		List<Goods> list = goodsService.selectGoods();
		model.addAttribute("list", list);
		return "Brand";
	}
// 找到品牌下所有的商品
	@RequestMapping("/selectGoods")
	public String selectGoods(Model model,Integer id) {
		List<Goods> list = goodsService.listGoods(id);
		for (Goods goods : list) {
			System.err.println(goods);
		}
		model.addAttribute("list", list);
		return "Goods";
	}
	//添加购物车
	@RequestMapping("/addShopping")
	@ResponseBody
	public Integer shopping(Integer id) {
		List<Shopping> l = goodsService.selectshopping(id);
		int i = 0;
		if(l==null) {
			//不存在
			 i = goodsService.addShopping(id);
			 i++;
		}
		//存在
		 i = goodsService.setShopping(id);
		return i;
	}
	//展示购物车
	@RequestMapping("/selectShopping")
	public String selectShopping(Model model) {
		List<Shopping> list =  goodsService.selectShopping();
		for (Shopping shopping : list) {
			System.out.println(shopping);
		}
		model.addAttribute("list", list);
		return "shopping";
	}
}
